<template>
    <childLayout activeType="thesisList" :showSidebar="false" :lunwenName="lunwenName">
        <div class="child-content">
            <div class="search-box">
				<span class="el-dropdown-link">
				    关键字
				</span>
				<!--
                <el-dropdown>                   
                    <template #dropdown>
                        
                        <el-dropdown-menu>
                            <el-dropdown-item>主题1</el-dropdown-item>
                            <el-dropdown-item>主题2</el-dropdown-item>
                        </el-dropdown-menu>
						
                    </template>
                </el-dropdown>
				-->
                <div class="search-input">
                    <el-input v-model.trim="searchText" style="height: 100%; width: 100%;" size="large"
                        placeholder="请输入关键字进行搜索" @keydown.enter="resetQuery"></el-input>
                </div>

                <div class="seach-icon" @click="resetQuery">
                    <img src="@/assets/images/search-icon.png" alt=""></img>
                </div>
            </div>
            <div class="filter-data-content">
                <div class="filter-box" v-if="cateList.length > 0">
                    <div class="item-filter-type">
                        <div class="item-filter-label">专业类别</div>
                        <div class="item-filter-list">
                            <div :class="['item-filter', oneIdx === index && 'item-filter-active']"
                                v-for="(val, index) in cateList" :key="index" @click="toSelectCate(index)">
                                {{ val.categoryName }}</div>
                        </div>
                    </div>
                    <div class="item-filter-type" v-if="twoList.length > 0">
                        <div class="item-filter-label">细分类别</div>
                        <div class="item-filter-list">
                            <div :class="['item-filter', twoIdx === index && 'item-filter-active']"
                                v-for="(val, index) in twoList" :key="index" @click="toSelectCateTwo(index)">
                                {{ val.categoryName }}</div>
                        </div>
                    </div>
                    <div class="item-filter-type" v-if="threeList.length > 0">
                        <div class="item-filter-label">细分类别</div>
                        <div class="item-filter-list">
                            <div :class="['item-filter', threeIdx === index && 'item-filter-active']"
                                v-for="(val, index) in threeList" :key="index" @click="toSelectCateThree(index)">
                                {{ val.categoryName }}</div>
                        </div>
                    </div>
                </div>

                <div class="search-section">
                    <el-form ref="form" :inline="true" :model="queryParams" size="default" label-width="80">
                        <el-row>
                            <el-col :span="8">
                                <div class="form-flex">
                                    <el-form-item label="字数">
                                        <el-input-number v-model="queryParams.startNumbers" :min="0" clearable
                                            :max="queryParams.endNumbers > 0 ? queryParams.endNumbers : 1000000"
                                            :controls="false" style="width: 100px; margin-right: 10px;" />
                                        —
                                        <el-input-number v-model="queryParams.endNumbers"
                                            :min="queryParams.startNumbers > 0 ? queryParams.startNumbers : 0" clearable
                                            :controls="false" style="width: 100px; margin-left: 10px;" />
                                    </el-form-item>
                                </div>
                            </el-col>
                            <el-col :span="8">
                                <div class="form-flex">
                                    <el-form-item label="下载次数">
                                        <el-input-number v-model="queryParams.startDownload" :min="0" clearable
                                            :max="queryParams.endDownload > 0 ? queryParams.endDownload : 1000000"
                                            :controls="false" style="width: 100px; margin-right: 10px;" />
                                        —
                                        <el-input-number v-model="queryParams.endDownload" clearable
                                            :min="queryParams.startDownload ? queryParams.startDownload : 0"
                                            :controls="false" style="width: 100px; margin-left: 10px;" />
                                    </el-form-item>
                                </div>
                            </el-col>
                            <el-col :span="6">
                                <div class="form-flex" label="查重">
                                    <div class="form-spaceBetween">
                                        <el-checkbox v-model="queryParams.isTraditionDuplicate" label="可过传统查重"
                                            size="large" />
                                        <el-checkbox v-model="queryParams.isAigcDuplicate" label="可过AIGC查重"
                                            size="large" />
                                    </div>
                                </div>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="8">
                                <el-form-item label="论文类型" prop="lunwenType">
                                    <el-select v-model="queryParams.lunwenType" placeholder="请选择" style="width: 236px;"
                                        clearable>
                                        <el-option :value="item.dictLabel" :label="item.dictLabel"
                                            v-for="item in searchTypeList" :key="item.dictCode">{{
                                            item.dictLabel}}</el-option>
                                    </el-select>
                                </el-form-item>

                            </el-col>
                            <el-col :span="8">
                                <el-form-item label="日期" prop="dateRange">
                                    <el-date-picker v-model="dateRange" type="daterange" clearable range-separator="至"
                                        style="width: 236px;" value-format="YYYY-MM-DD" start-placeholder="开始日期"
                                        end-placeholder="结束日期" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="6">
                                <div class="form-end">
                                    <el-button type="primary" @click="resetQuery">搜索</el-button>
                                </div>
                            </el-col>
                        </el-row>

                    </el-form>
                </div>

                <div class="data-table">
                    <el-table :data="tableData" style="width: 100%; border-radius: 16px 16px 0 0; "
                        @selection-change="handleSelectionChange">
                        <el-table-column type="selection" width="50" align="center" />
                        <el-table-column prop="productNo" label="论文编号" align="center" width="120"/>
                        <el-table-column prop="productName" label="题目" show-overflow-tooltip>
                            <template #default="scope">
                                <span class="product-name"  @click="hanldeDetail(scope.row.productUid)">{{ scope.row.productName }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="numbers" label="字数" align="center" width="80" />
                        <el-table-column prop="jifen" label="所需积分" align="center" width="80">
                            <template #default="scope">
                                <div class="item-score">
                                    <div class="item-score-icon"> <img src="@/assets/images/score-icon.png" alt="">
                                    </div>
                                    <div class="item-score-num">{{ scope.row.jifen }}</div>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="lunwenType" label="论文类型" align="center" width="80"/>
                        <el-table-column prop="createDate" label="上传日期" align="center" width="110" />
                        <el-table-column prop="downloadCount" label="下载次数" align="center" width="80"/>
                        <el-table-column label="是否可过传统查重" align="center" width="90">
                            <template #default="scope">
                                <div class="item-status-icon">
                                    <img v-if="scope.row.isTraditionDuplicate=='1'" src="@/assets/images/pass-icon.png"
                                        alt="">
                                    <img v-else src="@/assets/images/no-pass.png" alt="">
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="是否可过AIGC查重" align="center" width="90">
                            <template #default="scope">
                                <div class="item-status-icon">
                                    <img v-if="scope.row.isAigcDuplicate=='1'" src="@/assets/images/pass-icon.png" alt="">
                                    <img v-else src="@/assets/images/no-pass.png" alt="">
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="90">
                            <template #default="scope">
                                <div class="opt-btn">
                                    <div class="item-opt-img" @click="toCollectPaper(scope.row)">
                                        <el-tooltip :content="scope.row.isCollect == '1' ? '取消收藏' : '收藏'" effect="dark"
                                            placement="top">
                                            <img v-if="scope.row.isCollect == '1'" src="@/assets/images/star-active.png"
                                                alt="">
                                            <img v-else src="@/assets/images/start-icon.png" alt="">
                                        </el-tooltip>
                                    </div>
                                    <div class="item-opt-img" @click="toDownloadPaper(scope.row)">
                                        <el-tooltip content="下载" effect="dark" placement="top">
                                            <img src="@/assets/images/down-icon.png" alt="">
                                        </el-tooltip>
                                    </div>
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div class="pagination-batch">
                        <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :small="false"
                            layout="total, sizes, prev, pager, next, jumper" :total="total"
                            @size-change="handleSizeChange" @current-change="handleCurrentChange" />

                        <div>
                            <el-button type="primary" :disabled="multipleSelection.length === 0"
                                @click="toBatchCollect">批量收藏</el-button>
                            <el-button type="primary" :disabled="multipleSelection.length === 0"
                                @click="toBatchDownload">批量下载</el-button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </childLayout>
</template>

<script setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import childLayout from "@/layout/childLayout";
import { getPaperList, battleCollectPaper, batchDownloadPaper, changeCollect } from '@/api/index'
import { getSiteInfo, getMemberType } from '@/api/common'
const router = useRouter()
const route = useRoute()

// const activeUid = parseFloat(route.params.groupUid)
const params = ref({
    categoryUid: null,
    majorUidOne: null,
    majorUidTwo: null,
    majorUidThree: null
})
const queryParams = ref({
    startNumbers: null,
    endNumbers: null,
    startDownload: null,
    endDownload: null,
    startUpload: null,
    isTraditionDuplicate: null,
    isAigcDuplicate: null,
    lunwenType: null,
    startDate: null,
    endDate: null,
})
const lunwenName = ref('')
const majorList = ref([])
const cateList = ref([])
const oneIdx = ref(null)
const twoIdx = ref(null)
const twoList = ref([])
const threeIdx = ref(null)
const threeList = ref([])
// const cateUid = ref('')
const searchText = ref('')
const pageSize = ref(10)
const pageNum = ref(1)
const total = ref(100)
const multipleSelection = ref([])
const tableData = ref([])
const dateRange = ref([])
const searchTypeList = ref([])

watch(() => dateRange.value, (newVal, oldVal) => {
    if (newVal) {
        queryParams.value.startDate = newVal[0]
        queryParams.value.endDate = newVal[1]
    } else {
        queryParams.value.startDate = ''
        queryParams.value.endDate = ''
    }
})

const handleSelectionChange = (val) => {
    multipleSelection.value = val
}
const handleSizeChange = (val) => {
    pageSize.value = val
    getPaperListData()
}
const handleCurrentChange = (val) => {
    pageNum.value = val
    getPaperListData()
}

const toSelectHotSearch = (item) => {
    searchText.value = item
    resetQuery()
}

const resetQuery = () => {
    pageNum.value = 1
    getPaperListData()
}

const toSelectCate = (index) => {
    if (oneIdx.value !== index) {
        oneIdx.value = index
        twoList.value = cateList.value[index].children
        params.value.majorUidOne = cateList.value[index].categoryUid
        params.value.majorUidTwo = null
        params.value.majorUidThree = null
        twoIdx.value = null
        threeIdx.value = null
        threeList.value = []
    }
    resetQuery()
}

const toSelectCateTwo = (index) => {
    if (twoIdx.value !== index) {
        twoIdx.value = index
        threeList.value = twoList.value[index].children
        params.value.majorUidTwo = twoList.value[index].categoryUid
        params.value.majorUidThree = null
        threeIdx.value = null
    }
    resetQuery()
}

const toSelectCateThree = (index) => {
    if (threeIdx.value !== index) {
        threeIdx.value = index
        params.value.majorUidThree = threeList.value[index].categoryUid
    }
    resetQuery()
}

// const toDownload = (row) => {
//     router.push(`/thesisDownload/${10}`)
// }

const getHomeInfo = async () => {
    const res = await getSiteInfo()
    if (res) {
        let { data } = res
        majorList.value = data.majorList
		twoList.value = data.showMajorList
		let list = []
		if(params.value.categoryUid && twoList.value){
			twoList.value.forEach(item => {			  			
			    if (item.groupUid === Number(params.value.categoryUid)) {
			        list.push(item)
			    }
			})
		}
		twoList.value = list
		
		
		
        setCategoryList()
        getPaperListData()
    }
}

const setCategoryList = () => {
    let list = []
    // majorList.value.forEach(item => {
    //     if(item.groupUid === params.value.categoryUid) {
    //         list.push(item)
    //     }
    // })
    // cateList.value = [
    //     {
    //         categoryName: '全部',
    //         categoryUid: ''
    //     },
    //     ...list
    // ]

    majorList.value.forEach(item => {
        item.children = []
        let vals = majorList.value.filter(v => v.categoryPuid == item.categoryUid)
        if (vals.length > 0) {
            item.children = vals
        }

        if (item.groupUid === Number(params.value.categoryUid) && item.categoryDepth==0) {
            list.push(item)
        }
    })

    if (params.value.majorUidOne) {
        let findIdx = list.findIndex(item => item.categoryUid === Number(params.value.majorUidOne))
        if (findIdx !== -1) {
            oneIdx.value = findIdx
            twoList.value = list[findIdx].children
            params.value.majorUidTwo = null
            params.value.majorUidThree = null
            twoIdx.value = null
            threeIdx.value = null
            threeList.value = []
        }
    }

    cateList.value = list
}

const getPaperListData = async () => {
    let res = await getPaperList({
        pageNum: pageNum.value,
        pageSize: pageSize.value,
        // categoryUid: activeUid,
        // majorUidOne: cateUid.value,
        keyWord: searchText.value,
        ...params.value,
        ...queryParams.value,
        isTraditionDuplicate: queryParams.value.isTraditionDuplicate ? '1' : null,
        isAigcDuplicate: queryParams.value.isAigcDuplicate ? '1' : null,
    })
    if (res) {
        let { data } = res
        tableData.value = data
        total.value = res.total
    }
}

const toCollectPaper = async (item) => {
    let res = await changeCollect({
        objUid: item.productUid,
        objType: 'good',
    })
    if (res) {
        ElMessage.success(item.isCollect == '0' ? '收藏成功' : '取消收藏成功')
        getPaperListData()
    }
}

const toBatchCollect = async () => {
    let ids = multipleSelection.value.map(item => item.productUid)

    let res = await battleCollectPaper(ids)
    if (res) {
        ElMessage.success('批量收藏成功')
        getPaperListData()
    }
}

const toDownloadPaper = (item) => {
    ElMessageBox.confirm('确定下载该论文吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        let res = await batchDownloadPaper({ productIds: [item.productUid] })
        if (res) {
            let { data } = res
            toDownload(data, item.productNo)
            ElMessage.success('下载成功')
            useUserStore().getInfo()
        }
    })
}


const delay = 30000; // 每个元素遍历的延迟时间，单位为毫秒

const delayFunction = (ms) => new Promise(resolve => setTimeout(resolve, ms));

async function delayedForEach(array, callback, delay) {
  for (let i = 0; i < array.length; i++) {
    if(i > 0) {
        await delayFunction(delay);
    }
    
    callback(array[i], i, array);
  }
}

const toBatchDownload = () => {
    ElMessageBox.confirm('确定批量下载论文吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        let ids = multipleSelection.value.map(item => item.productUid)
        let idCodes = multipleSelection.value.map(item => item.productNo)
        let res = await batchDownloadPaper({ productIds: ids })
        if (res) {
            let { data } = res
            // toDownload(data, idCodes.join(','))
            let urls = []
            if(typeof data === 'string') {
                urls = data.split(',')
            }else {
                urls = data
            }

            delayedForEach(urls, (url, index) => {
                toDownload(url, url.split('/').slice(-1)[0].split('.')[0])
            }, delay);

            ElMessage.success('批量下载成功')
            useUserStore().getInfo()
            getPaperListData()
        }
    })
}

const toDownload = (url, name) => {
    const a = document.createElement('a');
    document.body.appendChild(a);
    a.style.display = 'none';
    a.href = url;
    a.download = `${name}_${new Date().getTime()}`;
    a.click();
}

const getSearchType = async () => {
    const res = await getMemberType('paper_app_type')
    if (res) {
        searchTypeList.value = res.data
    }
}

const hanldeDetail = (item) => {	
    router.push(`/thesisDownload/${item}`)
}

onMounted(() => {
    params.value.categoryUid = route.query.categoryUid
    params.value.majorUidOne = route.query.majorUid
    lunwenName.value = route.query.name
    getSearchType()
    getHomeInfo()
})
</script>

<style lang="scss" scoped>
.search-box {
    width: 1100px;
    height: 64px;
    border: 2px solid rgba(51, 133, 255, 1);
    border-radius: 80px;
    background: rgba(255, 255, 255, 1);
    display: flex;
    align-items: center;
    padding: 0 8px 0 24px;

    .el-dropdown-link {
        color: rgba(5, 11, 32, 1);
        font-size: 18px;
        line-height: 28px;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 108px;
		/*
        &::after {
            content: '';
            border: 4px solid rgba(5, 11, 32, 1);
            margin-left: 16px;
            transform: rotate(45deg);
            border-top-color: transparent;
            border-left-color: transparent;
            position: relative;
            top: -2px;
        }*/
    }

    .search-input {
        flex: 1;
        height: 36px;
        padding-left: 8px;
        border-left: 1px solid rgba(233, 233, 233, 1);
        margin-left: 12px;
    }

    .seach-icon {
        width: 48px;
        height: 48px;
        border-radius: 50%;
        background: rgba(51, 133, 255, 1);
        padding: 12px;
        cursor: pointer;
    }
}

.filter-data-content {
    width: 100%;
    border-radius: 40px 40px 0px 0px;
    margin-top: 16px;

    .filter-box {
        width: 1100px;
        height: auto;
        margin: 0 auto;
        border-radius: 16px;
        padding: 24px 24px 8px 24px;
        margin-bottom: 16px;
        background: rgba(245, 245, 245, 1);

        .item-filter-type {
            display: flex;

            &:not(:last-child) {
                border-bottom: 1px solid rgba(233, 233, 233, 1);
                margin-bottom: 16px;
            }

            .item-filter-label {
                color: rgba(5, 11, 32, 1);
                font-size: 14px;
                font-weight: 700;
                line-height: 30px;
                margin-right: 24px;
            }

            .item-filter-list {
                flex: 1;
                display: flex;
                flex-wrap: wrap;

                .item-filter {
                    color: rgba(145, 153, 163, 1);
                    font-size: 14px;
                    font-weight: 500;
                    line-height: 30px;
                    padding-bottom: 16px;
                    cursor: pointer;

                    &:not(:last-child) {
                        margin-right: 24px;
                    }
                }

                .item-filter-active {
                    color: rgba(51, 133, 255, 1);
                    font-weight: 700;
                }
            }
        }
    }

    .data-table {
        width: 1100px;
        height: auto;
        margin: 0 auto;
        border-radius: 16px;
        background: rgba(255, 255, 255, 1);
        padding: 2px 0 24px;
        position: relative;

        .product-name {
            color: rgba(51, 133, 255, 1);
            cursor: pointer;
        }

        .item-score {
            display: flex;
            align-items: center;
            justify-content: center;
            color: rgba(102, 102, 102, 1);
            font-size: 14px;
            font-weight: 500;
            line-height: 30px;

            .item-score-icon {
                width: 16px;
                height: 16px;
                margin-right: 4px;
            }
        }

        .item-status-icon {
            display: flex;
            align-items: center;
            justify-content: center;

            img {
                width: 16px;
                height: 16px;
            }
        }

        .opt-btn {
            display: flex;
            align-items: center;

            .item-opt-img {
                width: 16px;
                height: 16px;
                cursor: pointer;

                &:not(:last-child) {
                    margin-right: 24px;
                }
            }
        }

        .pagination-batch {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-top: 24px;
            padding: 0 24px;
        }
    }
}

.search-section {
    width: 1100px;
    height: auto;
    margin: 0 auto;
    border-radius: 16px;
    background: rgba(245, 245, 245, 1);
    padding: 24px 24px 8px 24px;
    margin-bottom: 16px;

    .form-flex {
        display: flex;
        align-items: center;
    }

    .form-end {
        display: flex;
        justify-content: flex-end;
    }

    .form-spaceBetween {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}

.search-input {
    ::v-deep {
        .el-input__wrapper {
            box-shadow: none;
        }
    }
}

::v-deep {
    .el-table th.el-table__cell {
        background: rgba(244, 247, 255, 1);
        border-bottom-color: transparent;
        color: rgba(5, 11, 32, 1);
    }

    label {
        font-weight: 400;
    }
}
</style>